﻿using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace CommonLibrary.SocketUtils
{
    public class SocketReceiveData : IDisposable
    {
        private static ArrayPool<byte> InternalPool = ArrayPool<byte>.Shared;

        private byte[] _buffer;
        public int Length { get; set; }

        /// <summary>
        /// 缓存区默认大小
        /// </summary>
        public const int BufferSize = 1024 * 1024 * 2; //2M

        public int AllocSize { get; private set; }

        public byte[] Buffer
        {
            get
            {
                if (disposedValue)
                    throw new ObjectDisposedException("[CacheBuffer]Obj");
                return _buffer;
            }
        }

        public Socket SocketClient { get; set; }
        public EndPoint RemoteEndPoint { get; set; }

        public SocketReceiveData(int allocSize = BufferSize)
        {
            AllocSize = allocSize;
            _buffer = InternalPool.Rent(AllocSize);
        }

        ~SocketReceiveData()
        {
            Dispose();
        }

        public void Reset() => Length = 0;

        #region Dispose
        private bool disposedValue;

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)
                    InternalPool.Return(_buffer);
                    _buffer = null;

                    SocketClient?.Dispose();
                    SocketClient = null;
                }
                disposedValue = true;
            }
        }

        public void Dispose()
        {
            // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }
        #endregion
    }
}